<template>
  <div class="page-container">
    <!-- 使用el-steps做为进度条 -->
    <el-steps :active="active - 1" align-center finish-status="success"
              class="steps-container">
      <el-step title="商品信息"/>
      <el-step title="商品详情"/>
      <el-step title="其他设置"/>
    </el-steps>
    <el-divider class="custom-divider"/>
    <el-form :model="goodsFrom" label-width="120px" :rules="rules" require-mark>
      <!--商品信息页面-->
      <div v-show="active === 1">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="goodsFrom.goodsName" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品分类" prop="classifyIds">
              <el-tree-select
                  v-model="goodsFrom.classifyIds"
                  :data="classifyList"
                  multiple
                  :props="{ children: 'children' ,label: 'classifyName',value: 'id' }"
                  check-strictly
                  placeholder="请选择分类"
                  clearable>
              </el-tree-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="goodsFrom.unit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品简介" prop="descText">
              <el-input type="textarea" v-model="goodsFrom.descText"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品封面图" prop="titleImage">
              <el-upload @click="openImageTitle" :disabled="true" action="#" list-type="picture-card"
                         :auto-upload="false">
                <el-icon v-if="!goodsFrom.titleImage">
                  <Plus/>
                </el-icon>
                <el-image v-else :src="imageBase + goodsFrom.titleImage"
                          style="width: 80px; height: 80px;"></el-image>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品轮播图" prop="bannerImage">
              <el-upload @click="openImageBanner" :disabled="true" action="#" list-type="picture-card"
                         :auto-upload="false">
                <el-icon v-if="!goodsFrom.bannerImage">
                  <Plus/>
                </el-icon>
                <el-image v-else :src="imageBase + goodsFrom.bannerImage"
                          style="width: 80px; height: 80px;"></el-image>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="商品规格">
              <el-radio label="1" v-model="goodsFrom.skuType">单规格</el-radio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="佣金设置">
              <el-radio label="1" v-model="goodsFrom.isRaio">单独设置</el-radio>
              <el-radio label="2" v-model="goodsFrom.isRaio">默认设置</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="goodsAttrList" border style="width: 100%">
              <el-table-column label="图片">
                <template #default="scope">
                  <el-upload @click="openImage" :disabled="true" action="#" list-type="picture-card"
                             :auto-upload="false">
                    <el-icon v-if="!scope.row.image">
                      <Plus/>
                    </el-icon>
                    <el-image v-else :src="imageBase + scope.row.image" style="width: 50px; height: 50px;"></el-image>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="售价">
                <template #default="scope">
                  <el-input v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="成本价">
                <template #default="scope">
                  <el-input v-model="scope.row.cost"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="原价">
                <template #default="scope">
                  <el-input v-model="scope.row.otPrice"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存">
                <template #default="scope">
                  <el-input v-model="scope.row.stock"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="商品编号">
                <template #default="scope">
                  <el-input v-model="scope.row.barCode"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="重量（kg）">
                <template #default="scope">
                  <el-input v-model="scope.row.weight"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="体积（m³）">
                <template #default="scope">
                  <el-input v-model="scope.row.volume"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="一级返佣" v-if="goodsFrom.isRaio===1">
                <template #default="scope">
                  <el-input v-model="scope.row.brokerage" ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="二级返佣" v-if="goodsFrom.isRaio===1">
                <template #default="scope">
                  <el-input v-model="scope.row.brokerageTwo"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
      <div v-if="active===2">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品详情">
              <!-- 工具栏 -->
              <Toolbar
                  id="toolbar-container"
                  :editor="editorRef"
                  :default-config="toolbarConfig"
                  :mode="mode"
              />
              <!-- 编辑器 -->
              <Editor
                  id="editor-container"
                  style="width: 100%; border: #cbc7c7 solid 1px;margin-bottom: 50px;"
                  v-model="goodsFrom.goodsDetail"
                  :default-config="editorConfig"
                  :mode="mode"
                  @on-change="handleChange"
                  @on-created="handleCreated"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div v-show="active===3">
        <el-row>
          <el-col :span="8">
            <el-form-item label="排序">
              <el-input-number v-model="goodsFrom.sort" :min="1" :max="1000"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="积分">
              <el-input-number v-model="goodsFrom.points" :min="1" :max="1000"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="虚拟销量">
              <el-input-number v-model="goodsFrom.number"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品推荐">
              <el-checkbox label="1">是否热卖</el-checkbox>
              <el-checkbox label="2">热门榜单</el-checkbox>
              <el-checkbox label="3">促销</el-checkbox>
              <el-checkbox label="4">精品推荐</el-checkbox>
              <el-checkbox label="5">首发新品</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动优先级">
              <span class="spantui" style="background:red">默认</span>
              <span class="spantui" style="background:#1e9fff">秒杀</span>
              <span class="spantui" style="background:#009688">活动</span>
              <span class="spantui" style="background:#feb900">拼团</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
  <el-row style="margin-top: 50px;">
    <el-col :span="24" style="text-align: center;">
      <el-button @click="up" v-if="active > 1">上一步</el-button>
      <el-button type="primary" @click="last" v-if="active < 3" class="next-btn">下一步</el-button>
      <el-button type="primary" v-if="active === 3" @click="submitFrom" class="submit-btn">保存</el-button>
    </el-col>
  </el-row>
  <el-dialog title="选择图片" width="70%" v-model="dialogImgVisible">
    <material v-if="dialogImgVisible" @selectImage="selectImage" :flag="flag"></material>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onBeforeUnmount, shallowRef, getCurrentInstance, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import material from '../goods/material.vue'
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import '@wangeditor/editor/dist/css/style.css'

// 引入Axios
const axios = getCurrentInstance().appContext.config.globalProperties.$axios;

// 富文本编辑器配置
const mode = 'default'
const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = {placeholder: '请输入商品详情...'}

// 响应式数据
const active = ref(1)
const goodsFrom = reactive({
  goodsName: '',
  classifyIds: '',
  unit: '',
  descText: '',
  titleImage: '',
  bannerImage: '',
  skuType: '1',
  isRaio: '1',
  goodsDetail: '',
  sort: 1,
  points: 100,
  number: 0
})
const goodsAttrList = reactive([{
  image: '',
  price: '',
  cost: '',
  otPrice: '',
  suk: '1',
  stock: '',
  barCode: '',
  weight: '',
  volume: '',
  brokerage: '',
  brokerageTwo: ''
}])
const dialogImgVisible = ref(false)
const imageBase = 'http://localhost:8081/uploads/'
const flag = ref('title')
const classifyList = ref([])
const rules = ref({
  goodsName: [
    {required: true, message: '请输入商品名称', trigger: 'blur'}
  ],
  classifyIds: [
    {required: true, message: '请选择商品分类', trigger: 'blur'}
  ],
  unit: [
    {required: true, message: '请输入商品单位', trigger: 'blur'}
  ],
  descText: [
    {required: true, message: '请输入商品描述', trigger: 'blur'}
  ],
  titleImage: [
    {required: true, message: '请上传商品主图', trigger: 'blur'}
  ],
  bannerImage: [
    {required: true, message: '请上传商品轮播图', trigger: 'blur'}
  ]
})

// 编辑器处理
const handleCreated = (editor) => {
  editorRef.value = editor
}
const handleChange = (editor) => {
  goodsFrom.goodsDetail = editor.getHtml()
}

// 步骤切换
const up = () => active.value--
const last = () => active.value++

// 表单提交
const submitFrom = async () => {
  try {
    // 保存商品信息
    let res = await axios.post('/goods/addGoods', goodsFrom)
    if (res.data.code === '1') {
      // 保存商品属性信息
      for (let i = 0; i < goodsAttrList.length; i++) {
        goodsAttrList[i].goodsId = res.data.data
        await axios.post('/goods/addGoodsAttr', goodsAttrList[i])
      }
    }
    ElMessage.success('商品保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 图片处理
const openImageTitle = () => {
  flag.value = 'title'
  dialogImgVisible.value = true
}
const openImageBanner = () => {
  flag.value = 'banner'
  dialogImgVisible.value = true
}
const openImage = () => {
  flag.value = 'sku'
  dialogImgVisible.value = true
}

const selectImage = (val) => {
  switch (flag.value) {
    case 'title':
      goodsFrom.titleImage = val.fileName
      break
    case 'banner':
      goodsFrom.bannerImage = val.fileName
      break
    case 'sku':
      goodsAttrList[0].image = val.fileName
      break
  }
  dialogImgVisible.value = false
}

// 获取商品分类信息
const getClassifyList = async () => {
  const res = await axios.post('/classify/list')
  classifyList.value = res.data.data
}

// 初始化加载分类
onMounted(getClassifyList)

// 销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

</script>
<style lang="scss">
:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
}

.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .steps-container {
    margin: 20px 0 40px;
  }

  .custom-divider {
    margin: 10px 0 30px;
  }

  .image-uploader {
    width: 150px;
    height: 150px;
    border: 1px dashed var(--primary-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: var(--success-color);
    }

    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .upload-image {
      width: 100%;
      height: 100%;
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
  }

  .action-buttons {
    margin-top: 40px;
    text-align: center;

    .el-button {
      min-width: 120px;
      padding: 12px 24px;
      transition: all 0.3s;
    }

    .next-btn {
      background: var(--primary-color);
      border-color: var(--primary-color);

      &:hover {
        opacity: 0.8;
      }
    }
  }

  // 活动标签样式
  .priority-tag {
    padding: 4px 8px;
    border-radius: 4px;
    color: white;
    margin-right: 8px;

    &.default {
      background: var(--danger-color);
    }

    &.seckill {
      background: #1e9fff;
    }

    &.activity {
      background: #009688;
    }

    &.group {
      background: #feb900;
    }
  }

  // 表格优化
  .el-table {
    margin-top: 20px;
    th {
      background: #f5f7fa;
    }
    .el-input__inner {
      width: 100%;
      min-width: 80px;
    }
  }
}
</style>
